package pers.kw.server.sentinel.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pers.kw.protocol.R;

import java.util.ArrayList;
import java.util.List;

@RestController
public class UserApiController {

    private static final Logger log = LoggerFactory.getLogger(UserApiController.class);

    private static final String RESOURCE = "USER-API-RESOURCE";

    @RequestMapping(value = "/crm/api/sentinel/getInfo")
    public R<String> getInfo() {
        Entry entry = null;
        try {
            entry = SphU.entry(RESOURCE);
            //资源code
            log.info("执行业务逻辑：{}", "getInfo");
            return R.ok("业务执行成功");
        } catch (BlockException e) {
            e.printStackTrace();
            return R.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "接口被限流");
        } finally {
            if (entry != null) {
                entry.close();
            }
        }
    }

    /**
     * 定义流控规则
     * 暂时注释掉，否则会影响注解式的流控规则
     */
    //@PostConstruct
    private static void initFlowRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule flowRule = new FlowRule();
        flowRule.setResource(RESOURCE);
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setCount(1L);
        rules.add(flowRule);
        FlowRuleManager.loadRules(rules);
    }
}
